package com.hxkj.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxkj.dao.UserLoginHistoryDao;
import com.hxkj.domain.po.SysUser;
import com.hxkj.domain.po.UserLoginHistory;
import com.hxkj.service.UserLoginHistoryService;
import com.hxkj.service.UserService;
import com.hxkj.utils.HttpClient;
import com.platform.common.domain.result.ResultMessageStruct;
import com.platform.common.domain.to.PageTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.hxkj.utils.IPUtil.getIpAddress;

/**
 * created by kezhijie on 2018/8/24 14:22.
 * email to kezhijie@hxoss.com
 */
@Service
@Slf4j
public class UserLoginHistoryServiceImpl implements UserLoginHistoryService {

    @Autowired
    private UserLoginHistoryDao userLoginHistoryDao;
    @Autowired
    private UserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessageStruct save(UserLoginHistory userLoginHistory) throws Exception {

        ResultMessageStruct resultMessageStruct = new ResultMessageStruct();

        int i = userLoginHistoryDao.saveSelective(userLoginHistory);
        if (i > 0) {
            resultMessageStruct.setCode(200);
            resultMessageStruct.setMessage("历史登录信息保存成功");
        } else {
            resultMessageStruct.setCode(500);
            resultMessageStruct.setMessage("信息保存失败，请核对后重试");
        }

        return resultMessageStruct;
    }

    @Override
    public PageInfo findByUserId(UserLoginHistory userLoginHistory, PageTo pageTo) throws Exception {
        if (pageTo.getPageNum() == null || pageTo.getPageSize() == null) {
            pageTo.setPageNum(1);
            pageTo.setPageSize(10);
        }

        Page<UserLoginHistory> page = PageHelper.startPage(pageTo.getPageNum(), pageTo.getPageSize());
        List<UserLoginHistory> list = userLoginHistoryDao.selectListByUserId(userLoginHistory);
        PageInfo<UserLoginHistory> pageInfo = new PageInfo<>(page);

        return pageInfo;
    }

    /**
     * 记录登录历史信息
     * @param request
     * @param sysUser 用户
     * @throws Exception
     */
    @Override
    public void recodeLoginHistory(HttpServletRequest request, SysUser sysUser) {
        try {

            String ip = getIpAddress(request);

            String physicalAddress = getPhysicalAddress(ip);

            UserLoginHistory loginHistory = new UserLoginHistory();

            SysUser existsSysUser = userService.existsUser(sysUser);

            loginHistory.setUserId(existsSysUser.getUserId());
            loginHistory.setLoginName(sysUser.getUserAccount());
            loginHistory.setLoginIp(ip);
            loginHistory.setLoginLocation(physicalAddress);
            loginHistory.setLoginTime(System.currentTimeMillis());

            save(loginHistory);
        } catch (Exception e) {
            log.error("记录用户登录信息失败，userId:" + sysUser.getUserId(), e);
        }
    }

    private String getPhysicalAddress(String ip) {
        Map<String, Object> param = new HashMap<>();
        param.put("ip", ip);
        try {
            String result = HttpClient.docGet("http://ip.taobao.com/service/getIpInfo.php", param);
            Map<String, Object> addressInfo = JSON.parseObject(result, Map.class);
            return addressInfo.get("region").toString() + addressInfo.get("city").toString();
        } catch (Exception e) {
            return "获取物理地址失败";
        }
    }
}
